﻿using Microsoft.Extensions.PlatformAbstractions;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;

namespace KeepAccounts.Common.Utilities
{
    public static class HttpHelper
    {

        /// <summary>
        /// 下载网络图片
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="path">保存路径</param>
        /// <returns></returns>
        public static bool DownloadImage(string url, string path)
        {
            WebRequest wreq = WebRequest.Create(url);
            try
            {
                HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
                Stream s = wresp.GetResponseStream();
                System.Drawing.Image img;
                img = System.Drawing.Image.FromStream(s);
                img.Save(path, ImageFormat.Png);   //保存

                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }

        /// <summary>
        /// 保存用户头像 并返回路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string DownloadHeader(string url)
        {
            var fileName = Guid.NewGuid().ToString().Replace("-", "") + ".png";//文件名称
            var uploadPath = Path.Combine("wwwroot/files", DateTime.Now.ToString("yyyyMMdd"));
            var path = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, uploadPath);
            var filepath = Path.Combine(path, fileName);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return DownloadImage(url, filepath) ? "/" + Path.Combine(uploadPath.Replace("wwwroot/", string.Empty), fileName).Replace('\\', '/') : "";
        }

    }
}
